<template>
    <div class="box">
        <div class="raw-select" v-if="bodyValue === 'raw'">
            <t-select size="medium" style="width: 80px;" v-model="rawSelectValue" :options="options" />
        </div>
        <n-scrollbar style="max-height: 230px;height: 230px;">
            <t-tabs v-model="bodyValue" theme="card" >
                <!-- none -->
                <t-tab-panel value="none" label="none">
                <p >
                    选项卡1
                </p>
                </t-tab-panel>
                <!-- form-data -->
                <t-tab-panel value="form-data" label="form-data">
                    <div>
                        <n-data-table
                        :key="(row:any) => row.key"
                        :columns="formColumns"
                        :data="formData"
                        />
                        <div class="add_btn_box">
                            <t-button @click="addFormRow" class="addData">+</t-button>
                        </div>
                    </div>
                </t-tab-panel>
                <!-- x-www-form-urlencoded -->
                <t-tab-panel value="x-www-form-urlencoded" label="x-www-form-urlencoded">
                <div>
                    <n-data-table
                    :key="(row:any) => row.key"
                    :columns="columns"
                    :data="data"
                    />
                    <div class="add_btn_box">
                        <t-button @click="addRow" class="addData">+</t-button>
                    </div>
                </div>
                </t-tab-panel>
                <!-- raw -->
                <t-tab-panel value="raw" label="raw">
                    <div>
                        <t-textarea v-model="textValue" />
                    </div>
                </t-tab-panel>
                <!-- binary -->
                <t-tab-panel value="binary" label="binary">
                <p >选项卡5</p>
                </t-tab-panel>
                <!-- GraphQL -->
                <t-tab-panel value="GraphQL" label="GraphQL">
                <p >选项卡6</p>
                </t-tab-panel>
            </t-tabs>
        </n-scrollbar>
    </div>
</template>

<script lang="ts" setup>
    import { watch, h, ref,defineComponent } from 'vue'
    //body的默认选项
    let bodyValue=ref('none')
    //raw的默认选项
    let rawSelectValue=ref('JSON')
    let textValue=ref('')

    //raw的select
    const options = [
    { label: 'JSON', value: 'JSON' },
    { label: 'text', value: 'text' },
    ];

    //form表格
    //数据类型定义
    interface FormRowData {
    key: number
    KEY: string
    VALUE: string|File|null
    TYPE: 'text'|'file'
    DESCRIPTION: string
    }

    //数据初始化
    const formData = ref<FormRowData[]>([
    {
        key: Date.now(),
        KEY: '',
        VALUE: '',
        TYPE: 'text',
        DESCRIPTION: ''
    }
    ])

    //列配置
    const formColumns = [
    {
        title: 'KEY',
        key: 'KEY',
        width: 225,
        render(row: FormRowData) {
        return h('input', {
            value: row.KEY,
            placeholder: 'Key',
            onInput: (e: any) => (row.KEY = e.target.value),
            style:'border: none !important;',
            class:"none-border-input",
        })
        }
    },
    {
        title: 'TYPE',
        key: 'TYPE',
        width: 225,
        render(row: FormRowData) {
        return h('select', {
            value: row.TYPE,
            onChange: (e: any) => {
            row.TYPE = e.target.value
            if (row.TYPE === 'text') {
                row.VALUE = ''
            } else {
                row.VALUE = null
            }
            },
            style:'border: none !important; width:100%;',
            class:"none-border-input",
        }, [
            h('option', { value: 'text' }, 'Text'),
            h('option', { value: 'file' }, 'File')
        ])
        }
    },
    {
        title: 'VALUE',
        key: 'VALUE',
        width: 225,
        render(row: FormRowData) {
        if (row.TYPE === 'file') {
            return h('input', {
            type: 'file',
            onChange: (e: any) => {
                const file = e.target.files?.[0]
                if (file) row.VALUE = file
            },
            style:'border: none !important;',
            class:"none-border-input",
            })
        } else {
            return h('input', {
            value: row.VALUE,
            placeholder: 'Value',
            onInput: (e: any) => (row.VALUE = e.target.value),
            style:'border: none !important;',
            class:"none-border-input",
            })
        }
        }
    },
    {
        title: 'DESCRIPTION',
        key: 'DESCRIPTION',
        render(row: FormRowData) {
        return h('input', {
            value: row.DESCRIPTION,
            placeholder: 'Description',
            onInput: (e: any) => (row.DESCRIPTION = e.target.value),
            style:'border: none !important;',
            class:"none-border-input",
        })
        }
    }
    ]

    //添加行
    function addFormRow() {
    formData.value.push({
        key: Date.now(),
        KEY: '',
        VALUE: '',
        TYPE: 'text',
        DESCRIPTION: ''
    })
    }



    // x-www表格

    // ========== 数据类型定义 ==========
    interface RowData {
    key: number
    KEY: string
    VALUE: string
    DESCRIPTION: string
    }

    // ========== 数据初始化 ==========
    const createData = (): RowData[] => {
    return Array.from({ length: 1 }).map((_, index) => ({
        key: index,
        KEY: '',
        VALUE: '',
        DESCRIPTION: ''
    }))
    }

    const data = ref<RowData[]>(createData())

    

    // ========== 根据 key 查找索引 ==========
    const getDataIndex = (key: number): number => {
    return data.value.findIndex(item => item.key === key)
    }

    // ========== 可编辑单元格组件：ShowOrEdit ==========
    // 必须用 defineComponent 才能使用 setup 和响应式
    const ShowOrEdit = defineComponent({
        props: {
            value: {
            type: String,
            default: ''
            },
            onUpdateValue: {
            type: Function,
            required: true
            },
            placeholder: {
            type: String,
            default: ''
            }
        },
        setup(props) {
            const isEdit = ref(false)
            const inputRef = ref<HTMLElement | null>(null)
            const inputValue = ref(props.value)

            // 同步外部 value 变化
            watch(() => props.value, (newVal) => {
            inputValue.value = newVal
            })

            // const handleChange = () => {
            // props.onUpdateValue(inputValue.value)
            // isEdit.value = false
            // }

             const handleInput = (e:any) => {
                const value=e.target.value
                inputValue.value=value
                props.onUpdateValue(value)
                isEdit.value = false
            }

            return () =>
                h('input', {
                    ref: inputRef,
                    value: inputValue.value,
                    placeholder: props.placeholder,
                    onUpdateValue: (v: any) => (inputValue.value = v),
                    onChange: handleInput,
                    onBlur: handleInput,
                    onClick: (e: MouseEvent) => e.stopPropagation(), // 防止冒泡
                    style:'border: none !important;',
                    class:"none-border-input",
                    })
        }
    })

    // ========== 列配置 ==========
    const columns = [
        {
            title: 'KEY',
            key: 'KEY',
            width: 300,
            render(row: RowData) {
            const index = getDataIndex(row.key)
            return h(ShowOrEdit, {
                value: row.KEY,
                onUpdateValue: (v: string) => {
                data.value[index].KEY = v
                console.log('我是body，xxx的key',v);
                },
                placeholder: 'Key'
            })
            }
        },
        {
            title: 'VALUE',
            key: 'VALUE',
            width: 300,
            render(row: RowData) {
            const index = getDataIndex(row.key)
            return h(ShowOrEdit, {
                value: row.VALUE,
                onUpdateValue: (v: string) => {
                data.value[index].VALUE = v
                },
                placeholder: 'Value'
            })
            }
        },
        {
            title: 'DESCRIPTION',
            key: 'DESCRIPTION',
            render(row: RowData) {
            const index = getDataIndex(row.key)
            return h(ShowOrEdit, {
                value: row.DESCRIPTION,
                onUpdateValue: (v: string) => {
                data.value[index].DESCRIPTION = v
                },
                placeholder: 'Description'
            })
            }
        }
    ]


    //表格加一行
    function addRow(){
        data.value.push({
            key: Date.now(), // 唯一 key
            KEY: '',
            VALUE: '',
            DESCRIPTION: ''
        })
    }

    defineExpose({
        getFormData() {
            console.log('✅ getFormData 被调用')
            console.log('formData:', formData.value)
            if(bodyValue.value==='form-data'){
                return {
                    tab:bodyValue.value,
                    data:formData.value
                        .filter((row:FormRowData)=>row.KEY && row.KEY.trim() !=='')
                        .map((row:FormRowData)=>({
                            key:row.KEY,
                            type:row.TYPE,
                            value:row.VALUE
                        }))
                }
            }
            else{
                 return {
                    tab: bodyValue.value,
                    data:data.value
                        .filter((row: RowData) => row.KEY && row.KEY.trim() !== '')
                        .map((row: RowData) => ({
                            key: row.KEY,
                            value: row.VALUE
                        }))
                }
            }
        },
        getRawData(){
            return {
                select:rawSelectValue.value,
                data:textValue.value
            }
        }
    })
    
    
</script>

<style scoped>
    .addData {
        background-color: #0052d9;
        color: #fff;
        border: 0px;
    }
    .add_btn_box {
        display: flex;
        margin-top: 10px;
    }
    .addData:hover {
        background-color: #0047ba;
    }
    :deep(.n-data-table-td),
    :deep(.n-data-table-th) {
        border-right: 1px solid #e8e8e8
    }
    :deep(.n-data-table-td:last-child),
    :deep(.n-data-table-th:last-child) {
        border-right: none;
    }
    :deep(.none-border-input:hover) {
        /* background-color: rgba(247, 247, 250, 1); */
        background-color: #fff;
    }
    .footer {
        height: 22.5vh;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .box {
        position: relative;
    }
    .raw-select {
        position: absolute;
        top: 5px;
        right: 260px;
        z-index: 10;
        background: #fff;
        padding: 4px;
        border-radius: 10px;

    }
    :deep(.t-textarea__inner) {
        height: 165px;
        margin-top: 15px;
    }
</style>